package cn.serenedream.housedecoration.serivce;
import java.math.BigDecimal;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.serenedream.housedecoration.dao.SaleProductsRepository;
import cn.serenedream.housedecoration.dao.SaleRepository;
import cn.serenedream.housedecoration.dao.SaleSaleProductsRepository;
import cn.serenedream.housedecoration.dto.SaleDTO;
import cn.serenedream.housedecoration.entity.Sale;
import cn.serenedream.housedecoration.entity.SaleProducts;
import cn.serenedream.housedecoration.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SaleService {
    @Autowired
    SaleRepository saleRepository;

    @Autowired
    SaleSaleProductsService saleSaleProductsService;

    @Autowired
    SaleProductsRepository saleProductsRepository;

    @Autowired
    private UserService userService;

    public User findUserById(String id) {
        Long userById = saleRepository.findUserById(id);
        return userService.findById(String.valueOf(userById));
    }

    public Long count() {
        return saleRepository.count();
    }

    public Page<Sale> list(Integer currentPage, Integer pageSize) {
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.by("id").descending());
        return saleRepository.findAll(pageable);
    }

    public Page<Sale> findByName(Integer currentPage, Integer pageSize, String name) {
        if (name == null || name.isEmpty()){
            return list(currentPage, pageSize);
        }
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.by("id").descending());
        return saleRepository.findByName(pageable, name);
    }

    @Transactional
    public void delete(String id) {
        saleSaleProductsService.deleteBySaleId(id);
        saleProductsRepository.deleteBySaleId(id);
        saleRepository.deleteBySaleId(id);
    }

    public void insert(Sale sale){
        saleRepository.insert(sale);
    }

    public void save(Sale sale) {
        saleRepository.save(sale);
    }

    public Page<Sale> findByUserNameContaining(String name, Pageable pageable) {
        return saleRepository.findByUser_NameContaining(name, pageable);
    }

    public Sale findById(String id) {
        return saleRepository.findById(Long.valueOf(id)).get();
    }
}
